package com.example.arwhack.ui.arw;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.example.arwhack.R;
import com.example.arwhack.data.model.OkHttpResponse;
import com.example.arwhack.data.model.TransactionRecord;
import com.example.arwhack.data.model.TransactionRecordAdapter;
import com.example.arwhack.ui.login.LoginActivity;
import com.example.arwhack.util.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class RecordsActivity extends AppCompatActivity {

    private List<TransactionRecord> dataList;

    private ArrayAdapter<TransactionRecord>  adapter;


    private SharedPreferences sp;

    private int reLoginCount = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            System.out.println("收到消息:"+msg.what + ":" + msg.obj);
            switch (msg.what){
                case 0:{
                    Toast.makeText(getApplicationContext(), (String)msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                case 1:{
                    adapter.clear();
                    adapter.addAll((List) msg.obj);
                    adapter.notifyDataSetChanged();
                }
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_records);
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorDark,getTheme()));
        ActionBar actionBar= getSupportActionBar();
        actionBar.hide();
        ListView listView = findViewById(R.id.dataView);
        listView.setDivider(null);
        //默认数据
        dataList = new LinkedList<>();
        TransactionRecord transactionRecord = new TransactionRecord();
        transactionRecord.setTransactionType("SELL");
        transactionRecord.setVirtualCoin("PSNT");
        transactionRecord.setCurrency("CCNY");
        transactionRecord.setUnitPrice((new BigDecimal(1.3001d)));
        transactionRecord.setCommissionMoney((new BigDecimal(30648.3243d)));
        transactionRecord.setCompleteMoney(new BigDecimal(30648.3243d));
        transactionRecord.setCommissionAmount(new BigDecimal(21787.46d));
        transactionRecord.setCompleteAmount(new BigDecimal(21787.46));
        transactionRecord.setTradeTime(new Date());
        dataList.add(transactionRecord);
        adapter = new TransactionRecordAdapter(this,R.layout.records_layout,dataList);
        listView.setAdapter(adapter);
        sp = getApplication().getSharedPreferences("arw_hack", Context.MODE_PRIVATE);
        String token = sp.getString("saved_token", "");
        String coin = sp.getString("saved_coin", "");
        String currency = sp.getString("saved_currency", "");
        System.out.println(token+","+coin+","+currency);
        loadRemoteData(token,coin,currency);
        //点击当前委托重新加载数据
        TextView currentCommissionText = (TextView)findViewById(R.id.currentCommissionText);
        currentCommissionText.setOnClickListener((view)->{
            loadRemoteData(token,coin,currency);
        });
        //点击标题返回登录
        TextView arwTitle = (TextView)findViewById(R.id.arwTitle);
        arwTitle.setOnClickListener((view)->{
            returnToLogin();
        });
    }

    private void returnToLogin(){
        sp = getApplication().getSharedPreferences("arw_hack", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.apply();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        setResult(Activity.RESULT_OK);
        finish();
    }

    private void loadRemoteData(String token,String coin,String currency){
        HttpUtil.getRecords(token, coin, currency ,
                new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        sendMessage(0,e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                        String responseString = response.body().string();
                        Type responseType = new TypeToken<OkHttpResponse<List<TransactionRecord>>>(){}.getType();
                        OkHttpResponse okHttpResponse = gson.fromJson(responseString, responseType);
                        sendMessage(0,"列表接口返回："+okHttpResponse.toString());
                        if (Boolean.TRUE.equals(okHttpResponse.getSuccess())) {
                            sendMessage(1,okHttpResponse.getData());
                        }
                        //登录过期
                        else if(new Integer(1500).equals(okHttpResponse.getCode())){
                            reLogin(token,coin,currency);
                        }else{
                            sendMessage(0,okHttpResponse.getMessage());
                        }
                    }
                });
    }

    private void reLogin(String token,String coin,String currency){
        if(reLoginCount > 3){
            sendMessage(0,"尝试自动重新3次以后还是错误，请检查用户名和密码！");
            return;
        }
        reLoginCount++;
        HttpUtil.login(sp.getString("saved_username", "undefined"), sp.getString("saved_password", "undefined"), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendMessage(0,"尝试自动重新登录错误，异常信息为："+e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                String responseString = response.body().string();
                OkHttpResponse<String> okHttpResponse = gson.fromJson(responseString, OkHttpResponse.class);
                if (Boolean.TRUE.equals(okHttpResponse.getSuccess())) {
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("saved_token",okHttpResponse.getData());
                    editor.apply();
                    System.out.println("重新登录返回的token："+okHttpResponse.getData());
                    loadRemoteData(okHttpResponse.getData(),coin,currency);
                }else{
                    sendMessage(0,"尝试自动重新登录错误，异常信息为："+okHttpResponse.getMessage());
                }
            }
        });
    }

    private void sendMessage(int arg,Object msg){
        Message message = new Message();
        message.what = arg;
        message.obj = msg;
        handler.sendMessage(message);
    }
}
